import PointRoom from "../../Entities/PointRoom";
import LanguageMng from "../../Managers/LanguageMng";
import LanguageMngTs from "../../Managers/LanguageMngTs";

cc.Class({
    extends: cc.Component,

    properties: {
        row1:{
            default:null,
            type:cc.Prefab
        },

        bottomModel:{
            default:null,
            type:cc.Prefab
        },

        labelCountDown:{
            default:null,
            type:cc.Label
        },

        rowParent:{
            default:null,
            type:cc.Node
        },

        botFrameGreen:{
            default:null,
            type:cc.SpriteFrame
        },

        botFrameRed:{
            default:null,
            type:cc.SpriteFrame
        },

        botFrameYellow:{
            default:null,
            type:cc.SpriteFrame
        },

        botFrameBlue:{
            default:null,
            type:cc.SpriteFrame
        },

        labelTotalScore:{
            default:null,
            type:cc.Label
        },

        backPrefab:{
            default:null,
            type:cc.Prefab
        },

        darkBgFrame:{
            default:null,
            type:cc.SpriteFrame
        },

        lightBgFrame:{
            default:null,
            type:cc.SpriteFrame
        },

        btnClose:{
            default:null,
            type:cc.Node
        },

        buttonParent:{
            default:null,
            type:cc.Node,
        },

        bgNode:{
            default:null,
            type:cc.Node,
        },

        contentParent:{
            default:null,
            type:cc.Node
        }
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        cc.find("Canvas").on("dealinfo_start_count_down",this._onDealInfoStartCountDown.bind(this),this)
        // cc.find("Canvas").on("ui_update_dealinfo_totalscore",this.onUpdateDealInfoTotalScore.bind(this),this)
        cc.find("Canvas/UIManager").on("ui_update_dealinfo_totalscore",this.updateUserTotalScore.bind(this),this)
    },

    setDealInfoCloseStatus:function (showCloseBtn) {
        if(showCloseBtn){
            this.btnClose.active = true
            this.buttonParent.active = false
        }else {
            this.buttonParent.active = true
            this.btnClose.active = false
        }
    },

    initDealInfoData:function (gameMgr) {
        this.gameMgr = gameMgr
    },

    // onUpdateDealInfoTotalScore:function () {
    //     let items = this.rowParent.children
    //     for(let i=0;i<items.length;i++){
    //         let node = items[i]
    //         let nodeUid = node.id
    //         let userObj = cc.gg.dataMgr.getUser(nodeUid)
    //         cc.log("设置LabelTotalScore为：",userObj.score)
    //         cc.find("labels/LabelTotalScore",node).getComponent(cc.Label).string = userObj.score
    //     }
    // },

    updateUserTotalScore:function (id,totalScore) {
        cc.log("更新玩家总分")
        for(let i=0;i<this.rowParent.children.length;i++){
            let node = this.rowParent.children[i]
            if(node.id === id){
                node.getComponent("deal_info_row").setTotalScore(totalScore)
                return
            }
        }
        cc.error("更新用户",id,"的得分失败，找不到该用户")
    },

    updateUserCards:function (id, cards, mixCardNum) {
        cc.log("更新玩家本局手牌")
        for(let i=0;i<this.rowParent.children.length;i++){
            let node = this.rowParent.children[i]
            if(node.id === id){
                node.getComponent("deal_info_row").refreshCards(cards,null,mixCardNum || cc.gg.dataMgr.getMixCardNum())
                return
            }
        }
        cc.error("更新用户",id,"的牌组失败，找不到该用户")
    },

    updateUserScores:function (id, score, totalScore) {
        cc.log("更新玩家本局得分")
        for(let i=0;i<this.rowParent.children.length;i++){
            let node = this.rowParent.children[i]
            if(node.id === id){
                node.getComponent("deal_info_row").setScore(score)
                node.getComponent("deal_info_row").setTotalScore(totalScore)
                return
            }
        }
        cc.error("更新用户",id,"的得分失败，找不到该用户")
    },

    setWinUser:function (id) {
        cc.log("更新赢家")
        for(let i=0;i<this.rowParent.children.length;i++){
            let node = this.rowParent.children[i]
            if(node.id === id){
                node.getComponent("deal_info_row").setWaitting("%win%")
            }else {
                node.getComponent("deal_info_row").setWaitting("%lose%")
            }
        }
    },

    _onDealInfoStartCountDown:function (cd) {
        this._countTime = cd

        let string = LanguageMng.getSentence(136)
        if(!string){
            cc.error("No sentence on row 136!")
            return
        }
        let mainNameHolder = "%num"
        var regMain = new RegExp( mainNameHolder.toString() , "g" )
        string = string.replace(regMain,this._countTime)
        this.labelCountDown.string = string
        // cc.log("倒计时label现在的string是：",this.labelCountDown.string)

        if(this.bindingCountDown) this.unschedule(this.bindingCountDown)
        this.bindingCountDown = this.timeCallback.bind(this)
        this.schedule(this.bindingCountDown, 1)
    },

    timeCallback:function (dt) {
        if(this._countTime === 0){
            cc.log("倒计时结束，隐藏得分面板",this._countTime)
            this.unschedule(this.bindingCountDown)
            cc.find("Canvas/UIManager").emit("ui_hide_score")
            cc.gg.emitEvent("dealinfo_count_down_finish")
            return
        }
        this._countTime--
        let oriStr = LanguageMngTs.getSentence(313) //The game will start in %time second(s)
        let showTime = parseInt(this._countTime)
        let realStr = cc.gg.baseUtil.getNewStringByReplace(oriStr,"%time",showTime)
        this.labelCountDown.string = realStr    //"The game will start in " + this._countTime + " second(s)"

        // cc.log("倒计时label现在的string是：",this.labelCountDown.string)
    },

    stopCountDown:function () {
        this.unschedule(this.bindingCountDown)
    },

    start () {

    },

    // update (dt) {},

    initDealInfo:function (resultDatas,mixNum) {
        this._inited = true

        if(cc.gg.dataMgr.room instanceof PointRoom){
            this.labelTotalScore.string = LanguageMng.getSentence(170)
        }else {
            this.labelTotalScore.string = LanguageMng.getSentence(88)
        }
        this.labelCountDown.string = LanguageMng.getSentence(123)

        this.rowParent.removeAllChildren()
        for(let key in resultDatas){
            let userObj = resultDatas[key]
            if(!userObj) continue

            let newRow = cc.instantiate(this.row1)
            newRow.id = userObj.id

            this.rowParent.addChild(newRow)
            let bgFrame = userObj.id === cc.gg.dataMgr.getPlayerGameId() ? this.darkBgFrame : this.lightBgFrame
            this._initLabelRow(newRow,userObj,mixNum,false,bgFrame)
        }
    },

    _initLabelRow:function (node,showData,mixNum,initCards,bgFrame) {
        cc.log("初始化一行内容：",showData)
        let rowScript = node.getComponent("deal_info_row")

        let name = showData.name || ""
        let result = showData.result || LanguageMng.getSentence(176)
        let cards = showData.cards || []
        let score = showData.score || 0
        let totalScore = showData.totalScore || 0
        let matchs = [].concat(showData.matchs)

        rowScript.changeBgColor(bgFrame)
        rowScript.setName(name)
        rowScript.setWaitting(result)
        rowScript.setScore(score)
        rowScript.setTotalScore(totalScore)

        if(!node._initedPokers){
            if(initCards && cards.length){
                node._initedPokers = true
                rowScript.refreshCards(cards,matchs,mixNum)
            }else {
                rowScript.initEmptyCards()
            }
        }
    },

    _showBgMask:function () {
        this.bgNode.active = true
        this.bgNode.width = cc.winSize.width
        this.bgNode.height = cc.winSize.height
        let middlePos = cc.find("Canvas").convertToWorldSpaceAR(cc.Vec2.ZERO)
        this.bgNode.position = this.bgNode.parent.convertToNodeSpaceAR(middlePos)
    },

    _hideBgMask:function () {
        this.bgNode.active = false
        // this.bgNode.width = cc.winSize.width
        // this.bgNode.height = cc.winSize.height
        // this.bgNode.position = cc.Vec2.ZERO
    },

    showDealInfo:function () {
        cc.log("显示dealinfo了！")
        this.node.active = true
        this._showBgMask()
        cc.gg.logicUtil.windowEnterFromTop(this.contentParent)
    },

    hideDealInfo:function () {
        this._hideBgMask()
        cc.gg.logicUtil.windowOutToBottom(this.contentParent)
    },

    onContinueClicked:function (event) {
        cc.gg.tdUtil.doSendTdEvent("click_game_dealinfo_continue","DealInfo")
        cc.find("Canvas/UIManager").emit("ui_close_deal_info")
        cc.gg.emitEvent("dealinfo_count_down_finish")
    },

    onBackToLobby:function (event) {
        cc.logfl("leave from score panel")
        // cc.gg.dataMgr.getUser(cc.gg.dataMgr.getPlayerGameId()).trigger("leave")
        let cbYes = function () {
            let kv = {
                keys:["BackToLobby"],
                values:[cc.gg.enumConfig.BackToLobbyOpt.CONFIRM]
            }
            let jsonStr = JSON.stringify(kv)
            cc.gg.tdUtil.doSendTdEvent("game_quit","DealInfo",jsonStr)
        }
        let cbCancel = function () {
            let kv = {
                keys:["BackToLobby"],
                values:[cc.gg.enumConfig.BackToLobbyOpt.CANCEL]
            }
            let jsonStr = JSON.stringify(kv)
            cc.gg.tdUtil.doSendTdEvent("game_quit","DealInfo",jsonStr)
        }
        let cbDirectory = function () {
            let kv = {
                keys:["BackToLobby"],
                values:[cc.gg.enumConfig.BackToLobbyOpt.DIRECTORY]
            }
            let jsonStr = JSON.stringify(kv)
            cc.gg.tdUtil.doSendTdEvent("game_quit","DealInfo",jsonStr)
        }
        this.gameMgr.backToLobby(cbYes,cbCancel,cbDirectory)
    },

    onDealInfoClosed:function (event) {
        let room = cc.gg.dataMgr.room
        if(room.state === cc.gg.enumConfig.RoomNetState.COMMITTING
        && cc.gg.dataMgr.getPlayerUser().b_state === cc.gg.enumConfig.ReadyState.COMMITED){
            cc.find("Canvas/UIManager").emit("ui_show_view_node",true)
        }
        cc.find("Canvas/UIManager").emit("ui_close_deal_info")
    }
});
